import { ElMessage } from 'element-plus'
import { textFilter } from '@/utils/common'

/** 
 * ElMessageBox.confirm 确认弹窗逻辑
 * @param {String} action 操作名称
 * @param {Object} instance 弹窗实例
 * @param {Function} done 关闭弹窗的方法
 * @param {Function} callback 回调函数
 * @param {Array} args 回调函数参数
*/
export const useConfirm = async (action, instance, done,callback,...args) => {
  if (action === 'confirm') {
    try {
      instance.confirmButtonLoading = true
      instance.cancelButtonLoading = true
      const res = await callback?.(...args)
      return res
    } finally {
      instance.confirmButtonLoading = false
      instance.cancelButtonLoading = false
      done()
    }
  } else {
    done()
  }
}

/**
 * 复制到剪切板
 * @param {String} text 复制的文本
 * @param {Function} callback 回调函数
 * @param {Array} args 回调函数参数
 */
export const useCopyText = async (text,callback,...args) => {
  try {
    await navigator.clipboard.writeText(text)
    callback?.(...args) ?? ElMessage.success('复制成功')
  } catch (error) {
    console.log('复制失败', error)
    ElMessage.error('复制失败')
  }
}

/** 
 * 引入静态图片
 * @param {String} name 图片名称
 * @param {String} path 图片路径 默认icon
 * @param {String} suffix 后缀名 默认png
 * @returns {String} 图片路径
*/
export const useImportImg = (name, path = 'icon',suffix='png') => {
  return new URL(`../assets/${path}/${name}.${suffix}`,import.meta.url).href
}







/**
 * 本地手动分页管理
 * @param {Array} list 数据列表(ref包裹后的数据)
 * @param {Object} config 配置项
 * @param {Number} config.page 当前页 默认1
 * @param {Number} config.pageSize 每页条数 默认10
 * @param {Array} config.pageSizes 每页条数选择器的选项设置 [10,20,50,100,200]
 * @param {String} config.layout 分页组件布局，子组件名用逗号分隔 默认 total, sizes, prev, pager, next, jumper
 * @returns {Object} 各项参数
 */
export const useManualPaging = (list, config = {}) => {
  const _config = ref({
    page: 1,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100, 200],
    layout: 'total, sizes, prev, pager, next, jumper',
    ...config,
  })
  const listData = computed(() => {
    const { page, pageSize } = _config.value
    const start = (page - 1) * pageSize
    const end = page * pageSize
    return list.value.slice(start, end)
  })
  const total = computed(() => list.value.length)
  const handleSizeChange = (val) => {
    _config.value.pageSize = val
  }
  const handleCurrentChange = (val) => {
    _config.value.page = val
  }
  return {
    pageConfig:_config,
    listData,
    total,
    handleSizeChange,
    handleCurrentChange,
  }
}

/**
 * 管理表格实例,处理列表刷新
 * @param {Ref<any>} 表格实例 
 * @param {Boolean} isEdit 是否是编辑操作
 */
export const useTableRefresh = (tableRef,isEdit) => {
  if(isEdit){
    tableRef.value && tableRef.value.handlerSearch()
  }else{
    tableRef.value && tableRef.value.initSearch()
  }
}



/**
 * 扁平化转树形
 * @param {Array} list 扁平化数据
 * @param {String | Number} rootVale '' 
 * @param {*} parentId ''
 * @param {*} id ''
 * @returns 
 */
export const tranListToTreeData = (list, rootVale,parentId='parentId',id='id') => {
  const arr = []
  list.forEach(item => {
    if (item[parentId] == rootVale) {
// 找到之后 就要去找 item 下面有没有子节点const children = tranListToTreeData(list, item.id)
const children = tranListToTreeData(list, item[id])
      if (children.length) {
// 如果children的长度大于0 说明找到了子节点
        item.children = children
      }
      arr.push(item)
    }
  })
  return arr
}

/**
 * 文本数据批量处理
 * @param {object} form 表单数据
 */
export const useBatchTextFilter = (form)=>{
  for (let key in form) {
    form[key] = textFilter(form[key])
  }
}


/**
 * 自动定位校验位置
 */
export const elementPosition = () => {
  let el = document.querySelectorAll(".el-form-item__error")[0];
  el.scrollIntoView({ block: "center", behavior: "smooth" });
} 
